//
//  KLMSceneModeController.swift
//  KLM_GN
//
//  Created by Nic on 2025/3/11.
//

import UIKit

private let cellId = String(describing: KLMSceneModeCell.self)
private let maxSceneModeCount = 1000

class KLMSceneModeController: KLMBaseController {
    
    @IBOutlet weak var tipLabel: UILabel!
    @IBOutlet weak var collectionView: KLMBaseCollectionView!
    @IBOutlet weak var confirmBtn: KLMCommonButton!
    
    var device: KLMHomeDevice
    var deviceConfig: KLMRKDeviceConfig
    var rkScenes = [KLMRKScene]() {
        didSet {
            confirmBtn.isEnabled = (rkScenes.first(where: { $0.sceneButton == 1 }) != nil)
        }
    }
    var createdSceneId: Int? // 创建的场景ID
    
    var lastSelectIndex: IndexPath?
    weak var navRightItem: KLMBaseButton?
    
    private var deleteStatus = false {
        didSet {
            for (index, _) in modes.enumerated() {
                modes[index].isDelete = deleteStatus
            }
            collectionView.reloadData()
        }
    }
    var modes = [KLMCard]() {
        didSet {
            navRightItem?.isHidden = modes.count == 0 || modes.first?.subType == .add
        }
    }
    
    init(device: KLMHomeDevice, deviceConfig: KLMRKDeviceConfig) {
        self.device = device
        self.deviceConfig = deviceConfig
        super.init(nibName: "KLMSceneModeController", bundle: nil)
    }
    
    @MainActor required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let rightItem = KLMBaseButton()
        navigationItem.rightBarButtonItem = UIBarButtonItem.itemWithBaseButton(rightItem, target: self, action: #selector(manageMode(_:)), configBlock: { baseItem in
            baseItem.configStyle(with: KLMLocalizable.LANGLOC("Manage"), font: UIFont(safeName: "PingFangSC-Regular", size: 18), titleColor: appMainThemeColor)
            baseItem.configStyle(with: KLMLocalizable.LANGLOC("Done"), titleColor: appMainThemeColor, state: .selected)
        })
        navRightItem = rightItem
        
        loadRKSceneList()
    }
    // MARK: - 请求情景模式列表roomCode：situation_mode
    func loadRKSceneList(success: (() -> ())? = nil) {
        SVProgressHUD.show()
        KLMRequest.queryRKDeviceSceneList(meshId: device.meshId, uuid: device.uuid, roomCode: "situation_mode") { response in
            SVProgressHUD.dismiss()
            if let list = response as? [KLMRKScene] {
                self.rkScenes = list
                self.modes = KLMCard.situationModeCards(rkScenes: list)
                self.lastSelectIndex = nil
                if let index = list.firstIndex(where: { $0.sceneButton == 1 }) {
                    self.lastSelectIndex = IndexPath(item: index, section: 0)
                }
                if self.modes.count < maxSceneModeCount {
                    self.modes.append(KLMCard(type: .sceneMode, subType: .add, title: "创建模式"))
                }
                self.collectionView.reloadData()
                if let success = success {
                    success()
                }
            }
        } failure: { error in
            SVProgressHUD.dismiss()
            KLMHttpShowError(error)
        }
    }
    override func viewDidLoadConfig() {
        super.viewDidLoadConfig()
        tipLabel.configStyle(with: "快速选择", font: UIFont(safeName: "PingFangHK-Semibold", size: 18), titleColor: rgba(38, 38, 38, 1))
        confirmBtn.configStyle(with: "确定")
        confirmBtn.updateStyle(state: .normal, cornerRadius: confirmBtn.height*0.5)
        confirmBtn.isEnabled = false
        
        if let collectionView = collectionView {
            let layout = KLMCustomFlowLayout()
            layout.cellCountPerRow = 2
            layout.itemSize = CGSizeMake(164, 88)
            collectionView.collectionViewLayout = layout
            
            collectionView.register(UINib(nibName: cellId, bundle: nil), forCellWithReuseIdentifier: cellId)
            collectionView.delegate = self
            collectionView.dataSource = self
        }
    }

    @objc func manageMode(_ item: KLMBaseButton) {
        item.isSelected = !item.isSelected
        deleteStatus = !deleteStatus
    }
    // MARK: - 确定
    @IBAction func tapConfirm(_ sender: KLMCommonButton) {
        guard let selectIndex = modes.firstIndex(where: { $0.select }) else {
            SVProgressHUD.showInfo(withStatus: "请选择一个情景")
            return }
        if deleteStatus {
            SVProgressHUD.showInfo(withStatus: "请先退出编辑模式，再进行操作")
            return
        }
        if selectIndex < rkScenes.count {
            let scene = rkScenes[selectIndex]
            guard let config = scene.sceneConfig else {
                KLMAlertController.showAlertWithTitle(title: "请先配置该情景", message: nil)
                return }
            // 远程执行场景
            SVProgressHUD.show()
            //场景控制类型，0执行，1预览，2取消
            KLMRequest.remoteControlScene(meshId: scene.meshId ?? device.meshId, sceneId: scene.id, controlType: 0, groupControl: 0) { response in
                SVProgressHUD.showSuccess(withStatus: KLMLocalizable.LANGLOC("Success"))
               
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                    self.loadRKSceneList()
                }
            } failure: { error in
                SVProgressHUD.dismiss()
                KLMHttpShowError(error)
            }
        }
    }
}

extension KLMSceneModeController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return modes.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = KLMSceneModeCell.reusableCellCell(with: collectionView, reuseId: cellId, index: indexPath)
        cell.cellCard = modes[indexPath.item]
        cell.delegate = self
        return cell
    }
}

extension KLMSceneModeController: UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if deleteStatus {
            SVProgressHUD.showInfo(withStatus: "请先退出编辑模式，再进行操作")
            return
        }
        let mode = modes[indexPath.item]
        if mode.subType == .add {
            //最多定义 1000 个房间，创建字符 20 字以内?
            let modeCount = self.modes.count
            if modeCount <= maxSceneModeCount {
                let vc = KLMBaseModalController(type: .add, operTitle: mode.title, textFieldTip: "请输入模式名称", confirmBlock:  {[weak self] text, type in
                    if type == .add {
                        guard let self = self else { return }
                        self.addModeItem(name: text!, index: indexPath)
                    }
                })
                modalVc(vc: vc)
            } else {
                SVProgressHUD.showInfo(withStatus: "情景模式数量超过最大值！")
            }
        } else {
            selectIndex(indexPath: indexPath)
        }
    }
    // MARK: - 添加一个模式
    func addModeItem(name: String, index: IndexPath) {
        SVProgressHUD.show()
        KLMRequest.createScene(meshId: device.meshId, sceneName: name, deviceUuid: device.uuid) { response in
            SVProgressHUD.dismiss()
            self.loadRKSceneList { [weak self] in
                guard let self = self else { return }
                if self.rkScenes.count == 0 { return }
                let index = self.rkScenes.count - 1
                let settingVc = KLMBaseModeSettingController(type: .scene, rkScene: rkScenes[index])
                settingVc.titleText = "\(titleText ?? "情景模式")-\(modes[index].title)设置"
                navigationController?.pushViewController(settingVc, animated: true)
            }
        } failure: { error in
            SVProgressHUD.dismiss()
            KLMHttpShowError(error)
        }
    }
    // MARK: - 选中
    func selectIndex(indexPath: IndexPath) {
        if modes[indexPath.item].select { return }
        if let lastIndex = lastSelectIndex {
            if lastIndex != indexPath, lastIndex.item < modes.count {
                modes[lastIndex.item].select = false
            }
        }
        modes[indexPath.item].select = !modes[indexPath.item].select
        collectionView.reloadData()
        
        lastSelectIndex = indexPath
        confirmBtn.isEnabled = modes[indexPath.item].select
    }
}


extension KLMSceneModeController: KLMSceneModeCellDelegate {
    // MARK: - 删除
    func sceneModeCellTapDelete(cell: KLMSceneModeCell, index: IndexPath) {
        SVProgressHUD.show()
        KLMRequest.deleteScene(sceneId: rkScenes[index.item].id) { response in
            SVProgressHUD.dismiss()
            self.loadRKSceneList { [weak self] in
                guard let self = self else { return }
                if deleteStatus {
                    deleteStatus = rkScenes.count != 0
                }
            }
        } failure: { error in
            SVProgressHUD.dismiss()
            KLMHttpShowError(error)
        }
    }
    // MARK: - 编辑，进入参数配置页
    func sceneModeCellTapEdit(cell: KLMSceneModeCell, index: IndexPath) {
        if deleteStatus {
            SVProgressHUD.showInfo(withStatus: "请先退出编辑模式，再进行操作")
            return
        }
        let mode = modes[index.item]
        let settingVc = KLMBaseModeSettingController(type: .scene, rkScene: rkScenes[index.item])
        settingVc.titleText = "\(titleText ?? "情景模式")-\(mode.title)设置"
        settingVc.configBlcok = { [weak self] in
            guard let self = self else { return }
            self.loadRKSceneList()
        }
        navigationController?.pushViewController(settingVc, animated: true)
    }
    // MARK: - 长按，模式重命名
    func sceneModeCellLongPress(cell: KLMSceneModeCell, index: IndexPath) {
        if deleteStatus {
            SVProgressHUD.showInfo(withStatus: "请先退出编辑模式，再进行操作")
            return
        }
        let mode = modes[index.item]
        let vc = KLMBaseModalController(type: .rename, operTitle: "模式命名", textFieldTip: mode.title, confirmBlock:  {
            [weak self] text, type in
            if type == .rename {
                guard let self = self, let text = text else { return }
                SVProgressHUD.show()
                KLMRequest.updateSceneConfig(sceneId: rkScenes[index.item].id, sceneName: text) { response in
                    SVProgressHUD.showSuccess(withStatus: KLMLocalizable.LANGLOC("Success"))
                    
                    self.loadRKSceneList()
                    
                } failure: { error in
                    SVProgressHUD.dismiss()
                    KLMHttpShowError(error)
                }
            }
        })
        modalVc(vc: vc)
    }
}
